<?php
/**
 * User: zyj
 * Date: 2019/10/31
 */

namespace app\manage\middleware;

use app\admin\model\AuthRule;
use think\facade\Db;
use think\facade\Session;

class Auth
{
    /**
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zyj<535985755@qq.com>
     * Date: 2019/11/1
     */
    public function handle($request, \Closure $next)
    {

        list($module, $controller, $action) = [app('http')->getName(), $request->controller(), $request->action()];
        $this->reqest_url = $controller;
        // 登录状态检查
        $noLoginActs = ['Login']; //无需验证的控制器
        if (!in_array($this->reqest_url, $noLoginActs)) {
            if(session('user.id') == null){
                $url = '/manage/Login/index';
                $msg = ['code' => -1000, 'message' => '抱歉，您还没有登录获取访问权限！', 'url' => url($url)];
                return $request->isAjax() ? json($msg) : redirect($url);
            }
            if (!$this->authCheck()) {
                $msg = ['code' => -1001, 'message' => '抱歉，您还没有获取访问权限！'];
                return $request->isAjax() ? json($msg) : redirect('javascript:history.back(-1);'); ;
            }
        }
        //获取当前用户的权限列表
        return $next($request);
    }

    /**
     * 检查权限
     * @return array 返回结果
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zyj<535985755@qq.com>
     * Date: 2019/11/1
     */
    public function authCheck()
    {
        $noLoginActs = ['Login/index']; //无需验证的控制器
        if (!in_array($this->reqest_url, $noLoginActs)) {
            $this->hrefId = Db::name('auth_rule')->where('name', $this->reqest_url)->value('id');
            //当前管理员权限
            $map['a.id'] = Session::get('user.id');
            //print_r(session());
            $rules = Db::name('admin')->alias('a')
                ->join("auth_group_access aga", "a.id = aga.uid")
                ->join('auth_group ag', 'aga.group_id = ag.id', 'left')
                ->where($map)
                ->value('ag.rules');
            //用户权限规则id
            $adminRules = explode(',', $rules);
            // 不需要权限的规则id;
            $noruls =  Db::name('auth_rule')->where('status',"=",0)->column('id');
            $this->adminRules = array_merge($adminRules, $noruls);
//            print_r($this->adminRules);
            if ($this->hrefId) {
                // 不在权限里面，并且请求为post
                if (!in_array($this->hrefId, $this->adminRules)) {
                    return false;
                }
            } else {
                return false;
            }
        }
    }
}
